package com.zpark.transaction.service.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.shanjupay.paymentagent.api.conf.AliConfigParam;
import com.shanjupay.paymentagent.api.dto.AlipayBean;
import com.shanjupay.paymentagent.api.dto.PaymentResponseDTO;
import com.zpark.jushanpay.common.domain.BusinessException;
import com.zpark.jushanpay.common.domain.CommonErrorCode;
import com.zpark.jushanpay.common.domain.RestResponse;
import com.zpark.jushanpay.common.util.*;
import com.zpark.transaction.api.dto.PayChannelParamDTO;
import com.zpark.transaction.api.dto.PayOrderDTO;
import com.zpark.transaction.api.service.IPayChannelService;
import com.zpark.transaction.api.service.ITransactionService;
import com.zpark.transaction.service.config.AlipayConfig;
import com.zpark.transaction.service.convert.IPayOrderConvert;
import com.zpark.transaction.service.feign.IPayChannelAgentControllerFeign;
import com.zpark.transaction.service.vo.OrderConfirmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 支付测试
 */
//@RestController
//@RequestMapping("/pay")
@Controller  // 将来需要返回视图的时候使用此注解
@Slf4j
public class PayController {

    @Autowired
    private AlipayConfig alipayConfig;
    @Autowired
    private ITransactionService transactionService;
    @Autowired
    private IPayChannelAgentControllerFeign payChannelAgentControllerFeign;
    @Autowired
    private IPayChannelService payChannelService;

    // 创建支付宝手机网站支付测试方法
    @RequestMapping("/h5_phone")
    public void testH5Phone(HttpServletResponse response){

        // 调用业务层方法，获取请求支付页面的form表单字符串
        // 1、创建支付宝客户端对象
        DefaultAlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getUrl(),
                alipayConfig.getAppid(),
                alipayConfig.getRsaPrivateKey(),
                alipayConfig.getFormat(),
                alipayConfig.getCharset(),
                alipayConfig.getZhiFuPublicKey(),
                alipayConfig.getSignType()
        );
        // 2、创建支付宝请求对象
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        // 设置同步回调地址
        request.setReturnUrl(alipayConfig.getReturn_url());
        // 设置异步回调地址
        request.setNotifyUrl(alipayConfig.getNotifyUrl());

        // 3、创建支付宝请求参数封装对象
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();

        String orderId = System.currentTimeMillis() + "";
        System.out.println(orderId);
        // 4、设置支付宝请求参数
        // 订单号
        model.setOutTradeNo(orderId);
        // 金额
        model.setTotalAmount("199.9");
        // 订单标题
        model.setSubject("华为蓝牙耳机3.0");
        // 用户取消支付回调
        model.setQuitUrl("https://310dx2074ys0.vicp.fun/h5/quit_pay");

        // 设置交易方式编码
        model.setProductCode("QUICK_WAP_WAY");

        // 将请求参数添加到请求对象当中
        request.setBizModel(model);

        // 5、调用支付宝客户端对象发送请求
        String resultForm = "";
        try {
            // 调用支付宝客户端发起请求
            AlipayTradeWapPayResponse resp = alipayClient.pageExecute(request);
            // 6、获取请求结果
            resultForm = resp.getBody();

            // 设置响应编码
            response.setContentType("text/html;charset=utf-8");

            PrintWriter writer = response.getWriter();
            writer.write(resultForm);
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 支付入口
     * @param ticket
     * @return
     */
    @RequestMapping(value="/pay_entry/{ticket}")
    public String payEntry(@PathVariable("ticket") String ticket, HttpServletRequest request){

        try{
            //将ticket的base64还原
            String ticketStr = EncryptUtil.decodeUTF8StringBase64(ticket);
            //将ticket（json）转成对象
            PayOrderDTO order = JSON.parseObject(ticketStr, PayOrderDTO.class);
            //将对象转成url格式
            //Stringurl=toParamsString(order);

            BrowserType browserType =
                    BrowserType.valueOfUserAgent(request.getHeader("user-agent"));


            switch(browserType){
                case ALIPAY:
                    //直接跳转收银台pay.html
                    return "forward:/pay_page?" + ParseURLPairUtil.parseURLPair(order);
                case WECHAT:
                    //获取授权码(待实现)
                    return "forward:/pay_page?" + ParseURLPairUtil.parseURLPair(order);
                default:
            }
        }catch(Exception e){
            e.printStackTrace();
            log.error(e.getMessage(),e);
        }

        return "forward:/pay_page_error";
    }


    /**
     * 确认支付——创建订单（调用支付渠道代理服务）
     * @param vo
     * @param request
     * @param response
     */
    @RequestMapping("/createAliPayOrder")
    public void createAlipayOrderForStore(OrderConfirmVO vo,
                                          HttpServletRequest request,
                                          HttpServletResponse response){
        // 将vo转为dto
        PayOrderDTO dto = IPayOrderConvert.INSTANCE.voToDto(vo);
        // 设置客户端ip
        dto.setClientIp(IPUtil.getIpAddr(request));

        // 调用业务层接口获取支付参数和支付实体
        String paramStr = transactionService.submitOrderByAli(dto);
        AlipayBean alipayBean = transactionService.createAlipayBean();

        // 调用feign接口获取支付宝h5支付页面
        RestResponse<PaymentResponseDTO> payOrderByAliWAP =
                payChannelAgentControllerFeign.createPayOrderByAliWAP(paramStr, alipayBean);
        // 获取支付页面数据
        String form = payOrderByAliWAP.getResult().getContent().toString();
        log.info(form);
        // 将页面返回给客户端
        try {
            // 设置响应编码
            response.setContentType("text/html;charset=utf-8");

            PrintWriter writer = response.getWriter();
            writer.write(form);
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
